package com.example.educationcommunity.controller;

import com.example.educationcommunity.dto.UserDTO;
import com.example.educationcommunity.mapper.UserMapper;
import com.example.educationcommunity.model.User;
import com.example.educationcommunity.model.UserExample;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class RankController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/rank/{type}")
    private String rank(@PathVariable(name = "type") Integer type,
                        Model model){
        List<User> users = new ArrayList<>();
        List<UserDTO> userDTOS = new ArrayList<>();
        if(type==1){
            UserExample example = new UserExample();
            example.createCriteria();
            example.setOrderByClause("active DESC");
            users = userMapper.selectByExample(example);
        }else if(type==2){
            UserExample example = new UserExample();
            example.setOrderByClause("question_count DESC");
            users = userMapper.selectByExample(example);
        }else {
            UserExample example = new UserExample();
            example.setOrderByClause("comment_count DESC");
            users = userMapper.selectByExample(example);
        }

        for(int i=0;i<users.size();i++)
        {
            UserDTO u=new UserDTO();
            BeanUtils.copyProperties(users.get(i),u);
            userDTOS.add(u);
            userDTOS.get(i).setRank(i+1);
        }
        model.addAttribute("users",userDTOS);
        return "rank";
    }
}
